//
//  Connection.m
//  SchoomzingExamples
//
//  Created by garrison on Fri Apr 20 2001.
//  Copyright (c) 2001 Standard Orbit Software, LLC. All rights reserved.
//
//  Permission is granted to use this code for any purpose, at your own risk.
//  No warranties are expressed or implied.

#import <OmniNetworking/OmniNetworking.h>
#import "Connection.h"

@implementation Connection

- (void) processConnection
{
    // processing of the connection in this server is pretty minimal.
    // Read a line of input from the client and echo it back to the
    // client.  If the line is "STOP", then set the server up to exit.
    
    NSAutoreleasePool *pool = nil;
    ONSocketStream *stream = nil;
    NSString *inFromClient = nil;
    
    pool = [[NSAutoreleasePool alloc] init];
    // Create an autorelease pool to contain memory used in this scope.

    stream = [ONSocketStream streamWithSocket: mySocket];
    // Put an ONSocketStream object on the mySocket to simplify reading.

    do {

        NS_DURING {
            inFromClient = [stream readLine];
            // Read a line from the client.  Will read up to a NL or CRNL.

            [stream writeFormat:@"%@: %@ received connection from %@\r\n", 
                [NSCalendarDate calendarDate],  [ONHost localHostname],
                [[mySocket remoteAddressHost] hostname]];
            // Write a formatted header back to the client.
        
            [stream writeFormat:@"%@\r\n", [inFromClient uppercaseString]];
            // Echo the input line back to the client.
        }
        NS_HANDLER {
            NSLog(@"While processing connection, exception %@ was raised",
                [localException name]);
            break;
        }
        NS_ENDHANDLER
                  

        // In this example, we're done talking to the client so we'll initiate
        // the closing of the connection with abortSocket:.  In a real app, the
        // application-level protocol would probably dictate when the connection
        // with the client should end.
        [mySocket abortSocket];
        break;
    

    } while(1);
    // Loop forever processing the connection with the client.  A raised exception or
    // the receipt of an application-level protocol command to close the connection
    // should cause a break out of the loop.        

    [pool release];

}



- initWithConnectedSocket: (ONTCPSocket*) aSocket
{
    self = [super init];
    if ( self ) 
    {

        if ( [aSocket isConnected] )
            mySocket = [aSocket retain];
        else
            return nil;
        // We should initialized with connected socket, so if not, return
    }
    
    return self;
}

- (void) dealloc
{
    [mySocket release];
    [super dealloc];
}
@end
